package com.beiming.libra.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by fan heshui on 2018/5/3.
 *
 * 日期工具
 */
@Slf4j
public class IdCardUtil {

  public static final String DEF_CHATSET = "UTF-8";
  public static final String USER_AGENT =
      "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
  public static final String IDKEY = "b5556f0cf3948b1d3705dd75ef988593";
  public static final int DEF_CONN_TIMEOUT = 30000;
  public static final int DEF_READ_TIMEOUT = 30000;

  /**
   * 校验身份证和姓名是否有效
   */
  public static boolean identityAuthentication(String name, String idcard) {
    String result = null;
    String url = "http://op.juhe.cn/idcard/query"; // 请求接口地址
    Map<String, Object> params = new HashMap<>(); // 请求参数
    params.put("idcard", idcard); // 接收短信的手机号码
    params.put("realname", name);
    params.put("key", IDKEY);
    try {
      result = net(url, params, "GET");
      JSONObject object = JSON.parseObject(result);
      if (object != null && object.getIntValue("error_code") == 0
          && object.getJSONObject("result").getIntValue("res") == 1) {
        // 保存通过
        return true;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }

  /**
   *
   * @param strUrl 请求地址
   * @param params 请求参数
   * @param method 请求方法
   * @return 网络请求字符串
   * @throws Exception
   */
  public static String net(String strUrl, Map params, String method) throws Exception {
    HttpURLConnection conn = null;
    BufferedReader reader = null;
    String rs = null;
    try {
      StringBuffer sb = new StringBuffer();
      if (method == null || "GET".equals(method)) {
        strUrl = strUrl + "?" + urlEncode(params);
      }
      URL url = new URL(strUrl);
      conn = (HttpURLConnection) url.openConnection();
      if (method == null || "GET".equals(method)) {
        conn.setRequestMethod("GET");
      } else {
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
      }
      conn.setRequestProperty("User-agent", USER_AGENT);
      conn.setUseCaches(false);
      conn.setConnectTimeout(DEF_CONN_TIMEOUT);
      conn.setReadTimeout(DEF_READ_TIMEOUT);
      conn.setInstanceFollowRedirects(false);
      conn.connect();
      // 暂时没有地方使用到---注销 fan he shui
      // if (params != null && "POST".equals(method)) {
      // try {
      // DataOutputStream out = new DataOutputStream(conn.getOutputStream());
      // out.writeBytes(urlEncode(params));
      // } catch (Exception e) {
      // e.printStackTrace();
      // }
      // }
      InputStream is = conn.getInputStream();
      reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
      String strRead = null;
      while ((strRead = reader.readLine()) != null) {
        sb.append(strRead);
      }
      rs = sb.toString();
      JSONObject object = JSONObject.parseObject(rs);
      log.info("SMS Request: {}", params);
      if (Integer.valueOf(object.get("error_code") + "").equals(0)) {
        log.info("result:{}", object.get("result"));
      } else {
        log.info("result: {}:{}", object.get("error_code"), object.get("reason"));
      }
    } catch (IOException e) {
      log.error("{}", e);
    } finally {
      if (reader != null) {
        reader.close();
      }
      if (conn != null) {
        conn.disconnect();
      }
    }
    return rs;
  }

  // 将map型转为请求参数型
  public static String urlEncode(Map<String, Object> data) {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, Object> i : data.entrySet()) {
      try {
        sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8"))
            .append("&");
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    }
    return sb.toString();
  }
}
